using System.Data.Common;
using System.ComponentModel.DataAnnotations.Schema;
using System;
using System.ComponentModel.DataAnnotations;
using server.Services;
namespace server.Models;

public class User
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [KeyAttribute]
    public int ID { get; set; }
    [Required]
    [MinLength(2)]
    public string Name { get; set; } = null!;
    [Required]
    [MinLength(2)]
    public string NickName { get; set; } = null!;
    [Required]
    public string Password { get; set; } = null!;
    [Required]
    public int RoleID { get; set; }
    public virtual Role Role { get; set; } = null!;

    public User()
    {

    }
    public User(NewUser new_user, LibraryContext db)
    {
        Name = new_user.Name;
        NickName = new_user.NickName;
        Password = new_user.Password;
        var role = db.Roles.Where(r => r.Name.ToLower() == new_user.Role.ToLower()).FirstOrDefault();
        if (role is null)
        {
            throw new Exception("Can not find role with name " + new_user.Role);
        }
        RoleID = role.ID;
    }
}

public class NewUser
{
    [Required]
    [MinLength(2)]
    [Field(FieldType.String, "真实姓名", true)]
    public string Name { get; set; } = null!;
    [Required]
    [MinLength(2)]
    [Field(FieldType.String, "用户昵称", true)]
    public string NickName { get; set; } = null!;
    [Field(FieldType.String, "密码", true)]
    [Required]
    public string Password { get; set; } = null!;
    [Required]
    [Field(FieldType.Integer, "用户角色", true, @"/api/user/roles")]
    public string Role { get; set; } = null!;
}